﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Timers;
using System.Windows;
using System.Windows.Shell;
using NetPublisher.Properties;

namespace NetPublisher
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : IDisposable
    {
        private readonly Timer _runTimer;
        private readonly Timer _currentFileTimer;
        private int _secondsLeft = 5;

        private AutoPublisher _autoPublisher;

        private ProcessDoneEventArgs _lastEvents;

        public MainWindow()
        {
            InitializeComponent();
            _runTimer = new Timer(1000);
            _runTimer.Elapsed += _runTimer_Elapsed;
            _currentFileTimer = new Timer(100);
            _currentFileTimer.Elapsed += _currentFileTimer_Elapsed;
            cbNewOnly.IsChecked = Settings.Default.OnlyNew;
            var listener = new DebugOutputListener();
            listener.DebugMessage += listener_DebugMessage;
            Debug.Listeners.Add(listener);
        }

        void listener_DebugMessage(object sender, DebugMessageArgs e)
        {
            RunInUiThread(()=> { tbLog.AppendText(e.Message); tbLog.ScrollToEnd(); });
        }

        void _currentFileTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Dispatcher.Invoke(new Action(UpdateCurrentProcess));
        }
        
        private void RunInUiThread(Action action)
        {
             Dispatcher.Invoke(action);
        }
        //void _autoPublisher_PublishProcess(object sender, ProcessDoneEventArgs e)
        //{
        //    _lastEvents = e;
        //    Dispatcher.Invoke(new Action(UpdatePublishProcess));
        //}

        //private void UpdatePublishProcess()
        //{
        //    if (_lastEvents == null)
        //        return;
        //    taskBarInfo.ProgressValue = (progressPublish.Value = _lastEvents.Percents) / 100.0;
        //    lblFilePath.Content = _lastEvents.FilePath;
        //}

        private void UpdateCurrentProcess()
        {
            taskBarInfo.ProgressValue = (progressPublish.Value = _autoPublisher.CurrentProgressPercents) / 100.0;
            lblFilePath.Content = _autoPublisher.CurrentPath;
        }

        private void _autoPublisher_PublishFinished(object sender, EventArgs e)
        {
			Dispatcher.Invoke(new Action(Close));
			//_secondsLeft = 2;
			//_runTimer.Interval = 2000;
			//_runTimer.Elapsed -= _runTimer_Elapsed;
			//_runTimer.Elapsed += (s, args) => Dispatcher.Invoke(new Action(Close));
			//_runTimer.Start();
        }

        private void _runTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _secondsLeft--;
            Dispatcher.Invoke(new Action(UpdateStartPublishTimer));
        }

        private void UpdateStartPublishTimer()
        {
            if (_secondsLeft >= 0)
                btnYes.Content = string.Format(CultureInfo.CurrentCulture, "Yes ({0})", _secondsLeft);
            if (_secondsLeft == 0)
                btnYes_Click(btnYes, null);
            else if (_secondsLeft < 0)
            {
                _runTimer.Stop();
                WindowState = WindowState.Minimized;
            }
        }

        private void StartPublish()
        {
            _runTimer.Stop();
            _currentFileTimer.Start();
            _autoPublisher.Publish();
            Height = 320;
            tbLog.Visibility = Visibility.Visible;
            taskBarInfo.ProgressState = TaskbarItemProgressState.Normal;
            taskBarInfo.ProgressValue = 0;
            lblPublish.Visibility = Visibility.Collapsed;
            progressPublish.Visibility = Visibility.Visible;
            _secondsLeft = -1;
            _runTimer.Start();
        }

        public void Dispose()
        {
            if (_runTimer != null)
                _runTimer.Dispose();
            if (_currentFileTimer != null)
                _currentFileTimer.Dispose();
        }

        private void Window_SourceInitialized(object sender, EventArgs e)
        {
            _runTimer.Start();
        }

        private void btnYes_Click(object sender, RoutedEventArgs e)
        {
            if (!_autoPublisher.IsWorking)
                StartPublish();
            else
            {
                _autoPublisher.Paused = !_autoPublisher.Paused;
                taskBarInfo.ProgressState = _autoPublisher.Paused ? TaskbarItemProgressState.Paused : TaskbarItemProgressState.Normal;
            }
            btnYes.Content = _autoPublisher.Paused ? "Continue" : "Pause";
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            _runTimer.Stop();
            if (_autoPublisher.IsWorking && MessageBox.Show("The publishing in process. Are you sure to break it?", "Stop Publish", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                    return;
            _autoPublisher.Stop();
            _currentFileTimer.Stop();
            Close();
        }

        private void btnQuick_Click(object sender, RoutedEventArgs e)
        {
            _autoPublisher.QuickPublish = true;
            btnYes_Click(btnYes, e);
        }

        private void btnSettings_Click(object sender, RoutedEventArgs e)
        {
            _autoPublisher.OpenFtpSettings();
        }

        private void CbNewOnly_OnChecked(object sender, RoutedEventArgs e)
        {
            Settings.Default.OnlyNew = cbNewOnly.IsChecked.GetValueOrDefault();
        }

		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
			 _autoPublisher = new AutoPublisher();
            _autoPublisher.PublishFinished += _autoPublisher_PublishFinished;
            //_autoPublisher.PublishProcess += _autoPublisher_PublishProcess;
			lbServers.ItemsSource = _autoPublisher.FileParser.FtpServers;
			if (_autoPublisher.FileParser.FtpServers.Count > 0)
			{
				lbServers.SelectedIndex = 0;
				lbServers.SelectedItem = _autoPublisher.FileParser.FtpServers[0];
				_autoPublisher.FileParser.FtpServers[0].IsSelected = true;
			}
		}

		private void Window_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			_runTimer.Stop();
			btnYes.Content = "Yes";
		}

		private void lbServers_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
		{
			foreach (var ftpConnectionString in _autoPublisher.FileParser.FtpServers)
			{
				ftpConnectionString.IsSelected = lbServers.SelectedItems != null && lbServers.SelectedItems.Contains(ftpConnectionString);
			}
		}
    }
}
